package com.sohu.peak.util.servlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.StaleObjectStateException;

import com.sohu.peak.util.Logger;
import com.sohu.peak.util.PeakSessionFactory;

public class HibernateSessionRequestFilter implements Filter {
	private static final Logger log = new Logger();

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		try {
			log.debug("Starting a database transaction");
			PeakSessionFactory.instance().getCurrentSession().beginTransaction();
			chain.doFilter(request, response);

			// Commit and cleanup
			log.debug("Committing the database transaction");
			PeakSessionFactory.instance().getCurrentSession().getTransaction().commit();

		} catch (StaleObjectStateException staleEx) {
			log.error("This interceptor does not implement optimistic concurrency control!");
			log.error("Your application will not work until you add compensation actions!");

			throw staleEx;
		} catch (Throwable ex) {
			// Rollback only
			ex.printStackTrace();
			try {
				if (PeakSessionFactory.instance().getCurrentSession().getTransaction().isActive()) {
					log.debug("Trying to rollback database transaction after exception");
					PeakSessionFactory.instance().getCurrentSession().getTransaction().rollback();
				}
			} catch (Throwable rbEx) {
				log.error("Could not rollback transaction after exception!", rbEx);
			}

			// Let others handle it... maybe another interceptor for exceptions?
			throw new ServletException(ex);
		}
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		log.debug("Initializing filter...");
		log.debug("Obtaining SessionFactory from static HibernateUtil singleton");

	}

	public void destroy() {
	}

}
